"""
chat room  Client
env python3.6
socket UDP

"""
from socket import *
import sys,os

# 服务器地址
ADDR = ('127.0.0.1',8888)

# 发送
def send_msg(sockfd,name):
	while True:
		try:
			text = input("")
		except KeyboardInterrupt:
			text = 'quit'
		if text.strip() == "quit":
			msg = "Q " + name
			sockfd.sendto(msg.encode(),ADDR)
			sys.exit("exit")
		msg = 'C %s %s'%(name,text)
		sockfd.sendto(msg.encode(),ADDR)

# 接收
def recv_msg(sockfd,name):
	while True:
		try:
			data,addr = sockfd.recvfrom(1024)
		except KeyboardInterrupt:
			sys.exit()
		# 从服务器收到EXIT退出
		if data.decode() == "EXIT":
			sys.exit()
		print(data.decode() + '\nspeak:',end='')


def main():
	sockfd = socket(AF_INET,SOCK_DGRAM)

	# 进入聊天室
	while True:
		name = input("用户名>")
		msg = 'L ' + name
		sockfd.sendto(msg.encode(),ADDR)
		# 接收反馈 OK & 
		data,addr = sockfd.recvfrom(128)
		if data.decode() == "OK":
			print("已进入聊天室")
			break
		else:
			print(data.decode())
	pid = os.fork()
	if pid < 0:
		sys.exit("Error!")
	elif pid == 0:
		send_msg(sockfd,name) # 子进程负责消息发送
	else:
		recv_msg(sockfd,name) # 父进程负责消息接收

if __name__ == "__main__":
	main()
